var util = require('../../utils/util.js')

Page({
  data: {
    InputBottom: 0,
    num: 0,
    chatList: [],
    userId: null,
    connection: false
  },
  SocketTaskObject: null,

  onShow() {
    this.WebSocketConnect()
  },
  onReady() {
    this.SocketTaskObject.onClose((res) => {
      console.log('服务端关闭', res)
      if (res.code == 1006) {
        // setInterval(this.WebSocketConnect, 3000)
      }
      this.setData({
        num: '未连接'
      })
    })

    
    this.SocketTaskObject.onOpen((res) => {
      console.log('连接打开', res)
    })
    this.SocketTaskObject.onError((error) => {
      console.log('连接错误', error.errMsg)
    })

    this.SocketTaskObject.onMessage((res) => {
      console.log('聊天室有信息...\n')
      try {
        const message = JSON.parse(res.data);
        this.handleMessage(message);
        console.log(message)
      } catch (error) {
        console.error('消息解析失败:', error);
      }
    })
  },

  /**
   * 处理消息
   * @param {Object} message 服务端返回的消息
   */
  handleMessage(message) {
    const chatList = this.data.chatList;
    const timestamp = new Date().toLocaleTimeString();

    switch (message.type) {
      case 'message':
        chatList.push({
          type: 'message',
          userId: message.userId,
          content: message.message,
          timestamp,
          isSelf: message.userId === this.data.userId //message.userId === this.data.userId
        });
        this.setData({
          num: message.users
        })
        break;

      case 'system':
        chatList.push({
          type: 'system',
          content: message.message,
          timestamp
        });
        this.setData({
          num: message.users
        })
        break;

      case 'error':
        wx.showToast({
          title: message.message,
          icon: 'error'
        });
        break;

      case 'other':
        this.setData({
          num: message.users
        })
        break;
    }

    this.setData({
      chatList
    });
  },
  /**
   * 建立ws连接
   */
  WebSocketConnect() {
    this.SocketTaskObject = wx.connectSocket({
      url: 'ws://192.168.31.22:8080',
      success: res => {
        console.log('连接建立', res)
      },
      fail(f){
        console.log('连接建立失败', f)
      }
    })
  },

  checkNickname() {
    this.SocketTaskObject.send({
      data: this.data.nickname,
      success: res => {
        console.log('成功发送', res)
        this.setData({
          userId: this.data.nickname
        })
      }
    })
  },

  /**
   * 发送信息
   */
  sendMessage() {
    if (this.data.msgText) {
      var message = {
        type: 'message',
        userId: this.data.userId,
        message: this.data.msgText,
        timestamp: new Date().toLocaleTimeString(),
        isSelf: true
      }
      this.SocketTaskObject.send({
        data: this.data.msgText,
        success: res => {
          console.log('成功发送', res, message)
          // this.handleMessage(message)
        }
      })
      this.setData({
        msgText: null
      })
    } else {
      wx.showModal({
        title: '错误',
        content: '消息不能为空',
      })
    }
  },

  /**
   * 输入框获得焦点时，将输入框位置提高
   */
  InputFocus(e) {
    this.setData({
      InputBottom: e.detail.height
    })
  },
  /**
   * 输入框失去焦点时，将输入框的位置降低0
   */
  InputBlur(e) {
    this.setData({
      InputBottom: 0
    })
  }
})